package com.github.wxpay.sdk;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.google.gson.Gson;
import com.huanying.framework.user.UserController;

@Controller
public class WXPayController {
	private static Logger logger = Logger.getLogger(UserController.class);

    //统一下单
    @RequestMapping(value = "/getOrder.do")
    public String getOrder(String total_fee,String jsoncallback)
            throws Exception {
        Map<String, String> reqData = new HashMap<String, String>();      
        Map<String, String> resData = new HashMap<String, String>();
        reqData.put("total_fee", total_fee);
        
        WXPay wxpay = null;
        //生成签名，填充数据
        reqData=wxpay.fillRequestData(reqData);
        //返回
        resData=wxpay.unifiedOrder(reqData,10*1000,10*1000);
        Gson gson=new Gson();
		String str=gson.toJson(resData);
		return jsoncallback+"("+str+")";
     }
   
    //异步通知
    @RequestMapping(value = "/asyncCom.do")
    public void asyncCom(HttpServletRequest request,HttpServletResponse response)
            throws Exception {
    	WXPay wxpay = null;
    	 InputStream inputStream ;  
         StringBuffer sb = new StringBuffer();  
         inputStream = request.getInputStream();  
         String s ;  
         BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
         while ((s = in.readLine()) != null){  
             sb.append(s);  
         }  
         in.close();  
         inputStream.close();  
         //解析xml成map  
         Map<String, String> m = new HashMap<String, String>();  
         m = WXPayUtil.xmlToMap(sb.toString()); 
         //过滤空 设置 TreeMap  
         SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
         Iterator it = m.keySet().iterator();  
         while (it.hasNext()) {  
             String parameter = (String) it.next();  
             String parameterValue = m.get(parameter);  
               
             String v = "";  
             if(null != parameterValue) {  
                 v = parameterValue.trim();  
             }  
             packageParams.put(parameter, v);  
         }  
         
         // 账号信息  
         String key = WXPayConfigImpl.getInstance().getKey(); // key  
   
         logger.info(packageParams);  
         //判断签名是否正确  
         if(WXPayUtil.isSignatureValid(m,key)) {  
             //------------------------------  
             //处理业务开始  
             //------------------------------  
             String resXml = "";  
             if("SUCCESS".equals((String)packageParams.get("result_code"))){  
                 // 这里是支付成功  
                 //////////执行自己的业务逻辑////////////////  
                 String mch_id = (String)packageParams.get("mch_id");  
                 String openid = (String)packageParams.get("openid");  
                 String is_subscribe = (String)packageParams.get("is_subscribe");  
                 String out_trade_no = (String)packageParams.get("out_trade_no");  
                   
                 String total_fee = (String)packageParams.get("total_fee");  
                   
                 logger.info("mch_id:"+mch_id);  
                 logger.info("openid:"+openid);  
                 logger.info("is_subscribe:"+is_subscribe);  
                 logger.info("out_trade_no:"+out_trade_no);  
                 logger.info("total_fee:"+total_fee);  
                   
                 //////////执行自己的业务逻辑////////////////  
                   
                 logger.info("支付成功");  
                 //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.  
                 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
                         + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
                   
             } else {  
                 logger.info("支付失败,错误信息：" + packageParams.get("err_code"));  
                 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                         + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
             }  
             //------------------------------  
             //处理业务完毕  
             //------------------------------  
             BufferedOutputStream out = new BufferedOutputStream(  
                     response.getOutputStream());  
             out.write(resXml.getBytes());  
             out.flush();  
             out.close();  
         } else{  
             logger.info("通知签名验证失败");  
         }  
    }
   
}